package com.demo.jfinal.job;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.demo.jfinal.model.ApiDownstream;
import com.demo.jfinal.model.SmsOrders;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.tx.Tx;

import cmpp.netty.SocketChannelMap;
import cmpp.pdu.Deliver;
import cmpp.sms.ByteBuffer;
import cmpp.sms.NotEnoughDataInByteBufferException;
import cmpp.sms.ShortContent;
import io.netty.channel.socket.SocketChannel;

/**
 *
 *获取状态报告数据，推送给cmpp客户
 */
public class Deliver2DownStateJob implements Job {
	private static Logger log = Logger.getLogger(Deliver2DownStateJob.class);

	/*
	 * 从表里拿数据向运营商发送
	 */
	@Before(Tx.class)
	public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

		Date date = new Date();

		List<SmsOrders> smsOrdersList = SmsOrders.dao.find(
				"SELECT T.* FROM SMS_ORDERS T WHERE 1=1 AND T.IS_DOWN_PUSH = 'N' AND T.DATE_TYPE = '0' and T.LAST_SEND_DATE <= ?", date);

		if (smsOrdersList == null || smsOrdersList.isEmpty()) {
			log.info("Request2DownPushstateJob无数据处理");
			return;
		} else {
			Db.batch("update sms_orders set IS_DOWN_PUSH = 'Y' where 1=1 and ID = ? ", "ID", smsOrdersList,
					smsOrdersList.size());
		}

		for (int i = 0; i < smsOrdersList.size(); i++) {
			SmsOrders smsOrder = smsOrdersList.get(i);
			int confId = smsOrder.getInt("CONF_ID");
			ApiDownstream apiDownstream = ApiDownstream.dao.getApiDownstreamCacheById(String.valueOf(confId));
			if (apiDownstream == null) {
				apiDownstream = ApiDownstream.dao.findFirst(
						"select * from sms_api_downstream_config c where 1=1 and PROTOCOL_TYPE = '2' and CONF_ID = ?",
						confId);
			}
			if (apiDownstream == null) {
				log.info("推送CMPP状态报告时未获取到ID=" + confId + "的客户配置信息");
				continue;
			}
			Deliver deliver = new Deliver();
			
			deliver.setMsgId(smsOrder.getStr("CUSTOMER_NO").getBytes());
			deliver.setSrcTermId(smsOrder.getStr("PHONE_NO"));
			byte b = 1;
			deliver.setIsReport(b);
			ShortContent sc = new ShortContent();
			sc.setDestTerminalId(smsOrder.getStr("PHONE_NO"));
			sc.setSubmitTime(new SimpleDateFormat("yyMMddHHmm").format(new Date()));
			sc.setDoneTime(new SimpleDateFormat("yyMMddHHmm").format(new Date()));
			sc.setSate("DELIVRD");
			sc.setMsgId(smsOrder.getStr("CUSTOMER_NO"));
			sc.setSmscSequence(smsOrder.getStr("PHONE_NO"));
			deliver.setSc(sc);
			
			log.info("状态报告给客户：" + confId + "的详情：" + deliver.dump());
			SocketChannel socketChannel = (SocketChannel) SocketChannelMap
					.get(String.valueOf(smsOrder.getInt("CONF_ID")));
			if (socketChannel != null) {
				socketChannel.writeAndFlush(deliver);
			} else {
				log.info("客户：" + confId + "socket未找到或已断开连接!!!");
			}
		}
	}
	public static void main(String[] args) {
		System.out.println(new SimpleDateFormat("yyMMddHHmm").format(new Date()));
	}

}
